package itsm.isperp.module.service.app;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.app.AppUserDefGrid;
import itsm.isperp.module.repository.app.AppUserDefGridMapper;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * 服务
 * 
 * @author lizx
 * @date 2015-11-24 14:07
 */
@Service
public class AppUserDefGridService extends BaseService<AppUserDefGrid> {

	@Autowired
	protected AppUserDefGridMapper appUserDefGridMapper;

	@Override
	public AppUserDefGridMapper getRepository() {
		return this.appUserDefGridMapper;
	}

	@Override
	public int saveOrUpdate(AppUserDefGrid entity, HttpServletRequest req) {
		Assert.notNull(entity, "对象不能为空");
		String username = ContextHolder.getLoginUsername();
		String id = this.findUserDefId(username, entity.getUrl(),
				entity.getGridId());
		entity.setUsername(ContextHolder.getLoginUsername());
		if (id == null) {
			entity.setId(HibernateUUIDGenerator.generate());
			this.appUserDefGridMapper.save(entity);
		} else {
			entity.setId(id);
			this.appUserDefGridMapper.update(entity);
		}
		return 1;

	}

	public String findUserDefId(String username, String url, String gridId) {
		String sql = "SELECT id FROM APP_USER_DEF_GRID WHERE username=? AND url=? AND grid_id=?";
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
		try {
			return jdbcTemplate.queryForObject(sql, String.class, username,
					url, gridId);
		} catch (Exception ex) {
			return null;
		}
	}

	public Map<String, Object> findUserDefGrid(String url, String gridId) {
		String username = ContextHolder.getLoginUsername();

		String sql = "SELECT COL_MODEL,PAGE_SIZE FROM APP_USER_DEF_GRID WHERE USERNAME=? AND URL=? AND GRID_ID=?";
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
		try {
			return jdbcTemplate.queryForMap(sql, username, url, gridId);
		} catch (Exception ex) {
			return null;
		}
	}

	public ResultMessage deleteUserDefGrid(String url, String gridId) {
		String username = ContextHolder.getLoginUsername();
		String sql = "DELETE FROM APP_USER_DEF_GRID WHERE USERNAME=? AND URL=? AND GRID_ID=?";
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
		jdbcTemplate.update(sql, username, url, gridId);
		return ResultMessage.success();
	}
}
